package main

import (
	"flag"
	"fmt"
	"os"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

var (
	conf = NewDefaultConf()
)

//cli参数
var (
	fileName string
	help     bool
)

type Conf struct {
	EndPoint   string
	AK         string
	SK         string
	BucketName string
}

//声明cli的参数
func init() {
	flag.StringVar(&fileName, "f", "", "上传文件的文件路径")
	flag.BoolVar(&help, "h", false, "使用说明")
}

func NewDefaultConf() *Conf {
	return &Conf{
		BucketName: "filetransferstation",
	}
}

func LoadConfigFromEnv() {
	conf.EndPoint = os.Getenv("ALI_OSS_ENPOINT")
	conf.AK = os.Getenv("ALI_AK")
	conf.SK = os.Getenv("ALI_SK")
}

func (c *Conf) Validator() error {
	if c.EndPoint == "" {
		return fmt.Errorf("EndPoint is required , please set EndPoint env")
	}
	if c.AK == "" {
		return fmt.Errorf("AK is required , please set AK env")
	}
	if c.SK == "" {
		return fmt.Errorf("SK  is required , please set SK  env")
	}
	return nil
}

func UploadFile(filename string) (fileURL string, err error) {
	client, err := oss.New(conf.EndPoint, conf.AK, conf.SK)
	if err != nil {
		err = fmt.Errorf("new oss object failed")
		return
	}
	bucket, err := client.Bucket(conf.BucketName)
	if err != nil {
		err = fmt.Errorf("find bucket is failed")
		return
	}
	err = bucket.PutObjectFromFile(filename, filename)
	if err != nil {
		err = fmt.Errorf("upload file %s is failed,maybe file is not exist", filename)
		return
	}

	//获取上传文件的链接
	return bucket.SignURL(filename, oss.HTTPGet, 60*60*24*3) //最后传入的是设置链接有效时间
}

//help参数时的使用说明
func usage() {
	fmt.Fprintf(os.Stderr, `cloud-station version: V0.0.1
	Usage: cloud-station -f <uplaod_file_path>
	Options:
	`)
	flag.PrintDefaults()
}

//解析用户传入的cli参数
func LoadArgsCli() {
	flag.Parse()
	if help {
		usage()
		os.Exit(0)
	}
}

func main() {
	//解析用户传入的cli参数
	LoadArgsCli()

	//加载配置
	LoadConfigFromEnv()

	//配置校验
	if err := conf.Validator(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	//上传文件
	fileURL, err := UploadFile(fileName)
	if err != nil {
		fmt.Println(err)
		os.Exit(2)
	}

	fmt.Printf("file:%s upload success\n", fileName)
	fmt.Printf("文件下载地址：%s", fileURL)
	fmt.Println("注意下载链接有效期为3天")
	os.Exit(0)
}
